package com.activemq.tx;

import com.activemq.MqHelloWorld;
import lombok.extern.slf4j.Slf4j;
import org.apache.activemq.ActiveMQConnectionFactory;
import org.springframework.boot.autoconfigure.jms.JmsProperties;

import javax.jms.*;

/**
 * MQ的事务
 *
 * @author wangwy16
 */
@Slf4j
public class MqTx {
    public static final String TX_QUEUE = "TX_QUEUE";

    public static void main(String[] args) throws Exception {
        ConnectionFactory factory = new ActiveMQConnectionFactory(MqHelloWorld.URL);
        Connection connection = factory.createConnection();
        connection.start();
        //写了true之后，不commit，则消息会不断的重复
        Session session = connection.createSession(true, JmsProperties.AcknowledgeMode.AUTO.getMode());
        //如果开启了事务，丹斯没有提交事务，会导致消息重复消费
        Queue queue = session.createQueue(MqTx.TX_QUEUE);
        MessageConsumer consumer = session.createConsumer(queue);
        consumer.setMessageListener((message -> {
            try {
                if (message instanceof TextMessage) {
                    log.error(((TextMessage) message).getText());
                }
            } catch (JMSException e) {
                log.error("出错", e);
            }
        }));
        System.in.read();
        //提交事务，防止重复消费
        session.commit();
        consumer.close();
        session.close();
        connection.close();
    }
}
